package com.CampusForum.community.controller;

import com.CampusForum.community.entity.DiscussPost;
import com.CampusForum.community.entity.Page;
import com.CampusForum.community.entity.User;
import com.CampusForum.community.service.DiscussPostService;
import com.CampusForum.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class HomeController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @GetMapping("/index")
    public String getIndexPage(Model model, Page page) {
        int count = discussPostService.getDiscussPostCount(0);

        page.setRows(count);

        page.setPath("/index");
        page.setFrom(page.getFrom());
        page.setTo(page.getTo());
        // 获取页面前十条数据
        List<Map<String, Object>> list = new ArrayList<>();
        List<DiscussPost> discussPosts = discussPostService.getDiscussPosts(0, page.getOffset(), page.getLimit());
        for (DiscussPost discussPost: discussPosts) {
            Map<String, Object> map = new HashMap<>();
            map.put("post", discussPost);
            // 根据用户id获取用户信息
            User user = userService.getUserById(discussPost.getUserId());
            map.put("user", user);
            list.add(map);
        }

        model.addAttribute("discussPosts", list);
        return "/index";
    }
}
